<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\Auth;
use app\api\helpers\Tree;
use app\api\helpers\v1\traits\FileUpload;
use app\api\model\v1\AdminLog;
use app\api\model\v1\Admins;
use app\api\model\v1\AuthGroup;
use app\api\model\v1\AuthRule;
use app\api\model\v1\Collect;
use app\api\model\v1\GatherCompany;
use app\api\model\v1\Rectification;
use app\api\model\v1\Score;
use app\api\validate\v1\AdminValidate;
use app\BaseController;
use think\exception\ValidateException;
use think\helper\Str;
use think\Request;

class Admin extends BaseController
{
    use FileUpload;

    /**
     * @User: 刘海龙
     * @Date: 2021/9/23
     * @Time: 17:57
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 用户列表
     */
    public function adminList()
    {
        //获取每页显示的条数
        $limit = $this->request->param('limit');
        $map = [];
        if ($this->request->has('username') && !empty($this->request->param('username'))) {
            $map[] = ['username', 'like', '%' . $this->request->param('username') . '%'];
        }
        if ($this->request->has('mobile') && !empty($this->request->param('mobile'))) {
            $map[] = ['mobile', 'like', '%' . $this->request->param('mobile') . '%'];
        }
        $data = Admins::with(['roles', 'unit'])->where($map)->paginate($limit)->each(function ($item, $key) {
            $pinjie = "";
            foreach ($item['roles'] as $k => $v) {
                $pinjie .= $v['name'] . ',';
            }
            $item['role_name'] = rtrim($pinjie, ',');
            if ($item['unit_id'] === 0) {
                $item['unit_name'] = '后台管理员';
            } else {
                $item['unit_name'] = $item['unit']['gather_company_title'] ?? '未知单位';
            }
            return $item;

        });
        return $this->response($data);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/23
     * @Time: 18:05
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 更新
     */
    public function adminUpdateShow()
    {
        $id = $this->request->param('id');
        $user = Admins::with(['unit'])->find($id);
        if (is_null($user)) {
            return $this->response(404, '此用户不存在');
        }
        // 检查用户权限
        $role_ids = array_column($user->roles()->select()->toArray(),
            'rules');//获取该用户所属角色rules
        if (in_array('*', $role_ids)) {
            $data =
                AuthRule::field('id,name')->where('is_open', AuthRule::OPEN_ONE)
                    ->select()
                    ->toArray();
        } else {
            $data = AuthRule::field('id,name')
                ->where('id', 'in', implode(',', $role_ids))
                ->where('is_open', AuthRule::OPEN_ONE)
                ->select()->toArray();
        }
        $url = [];
        foreach ($data as $key => $v) {
            $url[] = $v['name'];
        }
        $user['url'] = implode(',', $url);
        return $this->response($user->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/23
     * @Time: 18:04
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 新增或编辑
     */
    public function adminSave()
    {
        $id = $this->request->param('id', 0);
        try {
            $validator = $this->validate($this->request->param(),
                AdminValidate::rules($id),
                AdminValidate::msg());
            if ($validator) {
                $data = $this->request->except(['password_confirm']);
                if (empty($data['enter_unit_id'])) {
                    $data['enter_unit_id'] = 0;
                }
                if (intval($id) === 0) {
                    $data['password'] = password_hash(!empty($data['password']) ? $data['password'] : '111111', PASSWORD_DEFAULT);
                    $data['create_id'] = $this->request->uid ?? 0;
                    Admins::create($data);
                } else {
                    if (empty($data['password'])) {
                        unset($data['password']);
                    } else {
                        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
                    }
                    $user = Admins::find($id);
                    $user->update($data);
                }
                AdminLog::record(intval($id) === 0 ? '新增用户' : '编辑用户', $this->request->param(), $this->request->uid, $this->request->username);
                //添加用户角色中间表信息
                //GroupUserPivot::roleUserSave($user,$this->request->param('role_id'));
                return $this->response();
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->response(403, $e->getError());
        }
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/23
     * @Time: 18:03
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除用户
     */
    public function adminDelete($id)
    {
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            if (intval($id) === 1) {
                return $this->response(403, '超级管理员,不能删除');
            }
            $user = Admins::find($id);
            if (is_null($user)) {
                return $this->response(404, '此用户不存在');
            }
            //->force()
            $user->delete();
            AdminLog::record('删除用户', $this->request->param(), $this->request->uid, $this->request->username);
        }
        return $this->response();
    }


//    public function getLog(){
//        $agent = new Agent();
//        $headers = $agent->setUserAgent('Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36');
//        $agent->setHttpHeaders($headers);
//        halt($agent->browser());
//    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2021/12/30 16:55
     * @return \think\response\Json
     * 导入用户
     */
    public function importAdmin()
    {
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');

        $result = $this->saveImportExcel($file, 'import_excel', 'stage');
        $is_bool = Admins::saveAdminExcel($result, 1);
        if ($is_bool) {
            return $this->response();
        } else {
            return $this->response(403, '导入问卷失败');
        }
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/7 11:03
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取处自己之外的相同单位的列表
     */
    public function getSameUnitList()
    {
        $uid = $this->request->wx_id;
        $unit_id = $this->request->wx_unit_id;
        $admin = Admins::field('id,username,mobile,unit_id')->where(['unit_id' => $unit_id])->select()->toArray();
        $new_arr = [];
        foreach ($admin as $key => $value) {
            if ($value['id'] !== $uid) { //排除当前自己之外的所有人
                $new_arr[] = $value;
            }
        }
        return $this->response(array($new_arr));
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/10 9:05
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取上级单位
     */
    public function getSuperiorUnit()
    {
        $uid = $this->request->wx_id;
        $unit_id = $this->request->wx_unit_id;
        $company = GatherCompany::where(['type' => GatherCompany::IS_TYPE_TWO])->select()->toArray();
        $arr = Tree::instance()->init($company, 'pid')->getParent($unit_id);
        $new_arr = [];
//        foreach ($arr as $key => $value) {
//            if (isset($value['admin'])) {
//                foreach ($value['admin'] as $k => $v) {
//                    $group_ids = $this->auth->getGroupIds($v['id']);
//                    foreach ($group_ids as $k1 => $v1) {
//                        $group = AuthGroup::find($v1);
//                        if ($group['name'] === '整改管理员') { //当前角色为整改管理员
//                            $new_arr[] = $v;
//                        }
//                    }
//                }
//            }
//        }
        return $this->response(array($arr));
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/12 17:11
     * @return \think\response\Json
     * 查看当月的积分
     */
    public function getScoreCaseMonth(){
        $admin_id = $this->request->wx_id;
        $map = [];
        if(!$this->auth->isSuperAdmin($admin_id)){
            $group_id_arr = $this->auth->getGroups($admin_id)->toArray(); //获取当前角色的id
            $new_string = '';
            foreach ($group_id_arr as $k => $v) {
                $new_string .= $v['name'].',';
            }
            $new_string = rtrim($new_string,',');
            if(Str::contains($new_string,'整改')){
                $str = '整改';
            }else{
                $str = '采集';
            }
            $map[] = ['admin_id', '=',$admin_id];
        }else{
            $str = '总计';
        }

        $res = Score::where($map)->whereMonth('create_time')->sum('case_score');
        $count = Score::where($map)->whereMonth('create_time')->count();
        return $this->response(['score'=>$res,'str'=>$str,'count'=>$count]);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/14 13:52
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取当月明细
     */
    public function getScoreCaseMonthList(){
        $admin_id = $this->request->wx_id;
        $map = [];
        if(!$this->auth->isSuperAdmin($admin_id)){
            $map[] = ['admin_id', '=',$admin_id];
        }
        $res = Score::where($map)->with(['collect'=>['sample','project','community','unit'],'admin'])->whereMonth('create_time')->select();

        return $this->response($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/12 17:17
     * @return \think\response\Json
     * 我的整改统计
     */
    public function myReformCaseCount(){
        $admin_id = $this->request->wx_id;
        $res = Rectification::where(['admin_id'=>$admin_id,'status'=>Rectification::IS_STATUS_TWO])->count('id');
        return $this->response(['reform_count'=>$res]);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/12 17:20
     * @return \think\response\Json
     * 我的采集统计
     */
    public function myGatherCaseCount(){
        $admin_id = $this->request->wx_id;
        $res = Collect::where(['uid'=>$admin_id,'status'=>Collect::IS_STATUS_TWO])->count('id');
        return $this->response(['gather_count'=>$res]);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/14 16:16
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 修改用户信息
     */
    public function changeUserInfo(){
        $data = $this->request->param();

        $admin = Admins::with(['unit'=>['community']])->find($this->request->wx_id);

        if (is_null($admin)){
            return $this->response(403,'暂未找到该用户');
        }
        $admin->save(['username'=>$data['nickname'],'nickname' => $data['nickname'],'mobile'=>$data['mobile']]);
        if ($admin['unit'] === null) {
            $admin['unit'] = [
                'gather_company_title' => '未匹配到单位'
            ];
        }
        $admin['role'] = $admin->roles()->find(); //当前角色
        return $this->response($admin);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/14 16:32
     * @return \think\response\Json
     * 更改密码
     */
    public function changePassword()
    {
        $data = $this->request->param();
        $admin = Admins::find($this->request->wx_id);

        if (is_null($admin)){
            return $this->response(403,'暂未找到该用户');
        }
        if (!password_verify($data['oldPassword'], $admin->password)) {
            return $this->response(401, '原始密码错误');
        }
        if ($data['newPassword'] !== $data['confirmPassword']) {
            return $this->response(401, '两次密码输入不一致');
        }
        $admin->save(['password' => password_hash($data['newPassword'], PASSWORD_DEFAULT)]);
        return $this->response();
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/14 17:54
     * @return \think\response\Json
     * 积分列表 -- 月清空
     */
    public function getRankList(){
        $res = Score::field('admin_id,count(case_score) as case_score')->with(['admin'=>['unit']])
            ->group('admin_id')->whereMonth('create_time')->order('case_score desc')->select()->toArray();
        return $this->response($res);

    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 操作日志
     */
    public function getLogList(){
        $limit = $this->request->param('limit',10);
        $res = AdminLog::order('create_time desc')->paginate($limit);
        return $this->response($res);
    }
}
